<template>
  <div class="admin-dashboard">
    <div class="container">
      <h1 class="page-title">管理员仪表盘</h1>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
      
      <template v-else>
        <!-- 统计卡片 -->
        <el-row :gutter="20" class="stat-cards">
          <el-col :xs="24" :sm="12" :md="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-card-content">
                <div class="stat-icon pets-icon">
                  <i class="el-icon-pet"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ stats.totalPets }}</div>
                  <div class="stat-label">总宠物数量</div>
                </div>
              </div>
              <div class="stat-footer">
                <el-link :underline="false" @click="navigateTo('/admin/pets')">
                  查看所有宠物 <i class="el-icon-arrow-right"></i>
                </el-link>
              </div>
            </el-card>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-card-content">
                <div class="stat-icon users-icon">
                  <i class="el-icon-user"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ userCount }}</div>
                  <div class="stat-label">注册用户</div>
                </div>
              </div>
              <div class="stat-footer">
                <el-link :underline="false" @click="navigateTo('/admin/users')">
                  管理用户 <i class="el-icon-arrow-right"></i>
                </el-link>
              </div>
            </el-card>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-card-content">
                <div class="stat-icon applications-icon">
                  <i class="el-icon-document"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ stats.pendingApplications }}</div>
                  <div class="stat-label">待审核申请</div>
                </div>
              </div>
              <div class="stat-footer">
                <el-link :underline="false" @click="navigateTo('/admin/applications')">
                  查看申请 <i class="el-icon-arrow-right"></i>
                </el-link>
              </div>
            </el-card>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-card-content">
                <div class="stat-icon adoptions-icon">
                  <i class="el-icon-trophy"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ stats.successfulAdoptions }}</div>
                  <div class="stat-label">成功领养</div>
                </div>
              </div>
              <div class="stat-footer">
                <el-link :underline="false" @click="navigateTo('/admin/applications?status=approved')">
                  查看详情 <i class="el-icon-arrow-right"></i>
                </el-link>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <!-- 图表区域 -->
        <el-row :gutter="20" class="charts-section">
          <el-col :md="12" :sm="24">
            <el-card shadow="hover" class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>宠物类别分布</h3>
                </div>
              </template>
              <div class="chart-container" v-if="chartData.categoryData && chartData.categoryData.length > 0">                
                <el-pie-chart 
                  class="chart" 
                  :data="chartData.categoryData" 
                  :colors="chartColors"
                />
              </div>
              <div class="no-data" v-else>
                <i class="el-icon-data-analysis"></i>
                <p>暂无数据</p>
              </div>
            </el-card>
          </el-col>
          
          <el-col :md="12" :sm="24">
            <el-card shadow="hover" class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>最近30天申请趋势</h3>
                </div>
              </template>
              <div class="chart-container" v-if="chartData.applicationTrend && chartData.applicationTrend.dates && chartData.applicationTrend.dates.length > 0 && chartData.applicationTrend.counts && chartData.applicationTrend.counts.length > 0">
                <el-line-chart 
                  class="chart" 
                  :xData="chartData.applicationTrend.dates" 
                  :yData="chartData.applicationTrend.counts"
                  :name="'申请数量'"
                />
              </div>
              <div class="no-data" v-else>
                <i class="el-icon-data-analysis"></i>
                <p>暂无数据</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <!-- 最近活动 -->
        <el-row :gutter="20" class="recent-section">
          <el-col :md="16" :sm="24">
            <el-card shadow="hover" class="recent-card">
              <template #header>
                <div class="recent-header">
                  <h3>最近申请</h3>
                  <el-link :underline="false" @click="navigateTo('/admin/applications')">
                    查看全部
                  </el-link>
                </div>
              </template>
              <div class="recent-applications">
                <el-table :data="recentApplications" style="width: 100%" v-if="recentApplications.length > 0">
                  <el-table-column prop="user_name" label="申请人" width="120" />
                  <el-table-column prop="pet_name" label="宠物名称" width="120" />
                  <el-table-column prop="created_at" label="申请时间" width="180">
                    <template #default="scope">
                      {{ formatDate(scope.row.created_at) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                      <el-tag :type="getStatusType(scope.row.status)">
                        {{ formatStatus(scope.row.status) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120">
                    <template #default="scope">
                      <el-button link @click="viewApplication(scope.row.id)">
                        查看详情
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="no-data" v-else>
                  <i class="el-icon-document"></i>
                  <p>暂无申请数据</p>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :md="8" :sm="24">
            <el-card shadow="hover" class="recent-card">
              <template #header>
                <div class="recent-header">
                  <h3>评论预览</h3>
                </div>
              </template>
              <div class="comments-list">
                <div v-if="recentCommentsList.length === 0">
                  <el-empty description="暂无评论" />
                </div>
                <div v-else>
                  <div v-for="comment in recentCommentsList" :key="comment.id" class="comment-item">
                    <div class="comment-header">
                      <strong>{{ comment.username }}</strong> 
                      <span>评论了宠物 <strong>{{ comment.pet_name }}</strong></span>
                    </div>
                    <div class="comment-content">{{ comment.comment }}</div>
                    <div class="comment-date">{{ formatDate(comment.created_at) }}</div>
                  </div>
                  <div class="view-more-container">
                    <el-button type="primary" link @click="router.push('/admin/comments')">
                      查看更多 <el-icon><ArrowRight /></el-icon>
                    </el-button>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </template>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import AdminService from '@/services/AdminService'
import { ArrowRight } from '@element-plus/icons-vue'

// 定义API_URL
const API_URL = process.env.VUE_APP_API_URL || 'http://localhost:3000/api';

// 导入图表组件
import LineChartComponent from '@/components/charts/LineChart.vue'
import PieChartComponent from '@/components/charts/PieChart.vue'

export default {
  name: 'AdminDashboard',
  components: {
    ElPieChart: PieChartComponent,
    ElLineChart: LineChartComponent
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    const loading = ref(true)
    
    // 用户数量 - 专用变量
    const userCount = ref(0)
    
    // 实际用户数量，直接显示
    const actualUserCount = ref(0)
    
    // 统计数据
    const stats = reactive({
      totalPets: 0,
      totalUsers: 0,
      pendingApplications: 0,
      successfulAdoptions: 0
    })
    
    // 图表数据
    const chartData = reactive({
      categoryData: [],
      applicationTrend: {
        dates: [],
        counts: []
      }
    })
    
    // 图表颜色
    const chartColors = [
      '#409EFF', // 主色
      '#67C23A', // 成功色
      '#E6A23C', // 警告色
      '#F56C6C', // 危险色
      '#909399', // 信息色
      '#36B3B3', // 青色
      '#B366B3', // 紫色
      '#FF9900', // 橙色
      '#66B366', // 绿色
      '#B36666'  // 红色
    ]
    
    // 最近的申请
    const recentApplications = ref([])
    
    // 最近的评论列表
    const recentCommentsList = ref([])
    
    // 待处理任务
    const todoItems = ref([])
    
    const todoCategories = computed(() => {
      const categories = [
        { key: 'application', title: '待审核申请', count: 0 },
        { key: 'pet', title: '待更新宠物', count: 0 },
        { key: 'other', title: '其他任务', count: 0 }
      ]
      
      // 统计每个分类的数量
      categories.forEach(category => {
        category.count = todoItems.value.filter(item => item.category === category.key).length
      })
      
      return categories
    })
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '未知'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    // 格式化状态
    const formatStatus = (status) => {
      if (!status) return '未知';
      const statusMap = {
        pending: '待审核',
        approved: '已通过',
        rejected: '已拒绝',
        cancelled: '已取消'
      };
      return statusMap[status.toLowerCase()] || '未知';
    }
    
    // 获取状态标签类型
    const getStatusType = (status) => {
      if (!status) return 'info';
      const typeMap = {
        pending: 'warning',
        approved: 'success',
        rejected: 'danger',
        cancelled: 'info'
      };
      return typeMap[status.toLowerCase()] || 'info';
    }
    
    // 导航到指定路由
    const navigateTo = (path) => {
      router.push(path)
    }
    
    // 查看申请详情
    const viewApplication = (id) => {
      router.push(`/admin/applications?id=${id}`)
    }
    
    // 加载最近评论
    const loadRecentComments = async () => {
      try {
        const token = sessionStorage.getItem('token');
        if (!token) {
          console.error('认证错误');
          // 不显示详细错误给用户，因为这不是用户操作引起的
          return;
        }
        console.log('开始加载评论数据...');
        console.log('请求URL:', `${API_URL}/petcomments/recent`);
        console.log('请求头:', {
          'Authorization': `Bearer ${token}`,
          'x-auth-token': token
        });
        
        const response = await axios.get(`${API_URL}/petcomments/recent`, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'x-auth-token': token // 根据后端需求可能需要此字段
          }
        });
        
        console.log('评论API返回数据类型:', typeof response.data);
        console.log('评论API返回数据:', JSON.stringify(response.data));
        
        if (response.data && Array.isArray(response.data)) {
          recentCommentsList.value = response.data;
          console.log('处理后的评论列表长度:', recentCommentsList.value.length);
          console.log('处理后的评论列表:', JSON.stringify(recentCommentsList.value));
          
          // 打印第一条评论的所有字段，用于调试
          if (recentCommentsList.value.length > 0) {
            const firstComment = recentCommentsList.value[0];
            console.log('第一条评论的所有字段:');
            for (const key in firstComment) {
              console.log(`${key}: ${firstComment[key]}`);
            }
          }
        } else {
          console.warn('API返回的评论数据不是数组:', response.data);
          recentCommentsList.value = [];
        }
      } catch (error) {
        console.error('获取最近评论失败:', error);
        console.error('错误详情:', error.response ? error.response.data : '无响应数据');
        console.error('错误状态:', error.response ? error.response.status : '无状态码');
        recentCommentsList.value = []; // 失败时清空列表
        // 可以在这里添加一个不打扰用户的错误提示，或者只在控制台记录
      }
    };
    
    // 加载统计数据
    const loadStats = async () => {
      try {
        loading.value = true;
        
        // 检查令牌是否存在
        const token = sessionStorage.getItem('token');
        if (!token) {
          // 避免记录详细的认证错误
          console.error('认证错误');
          ElMessage.error('未找到认证令牌，请重新登录后再试');
          router.push('/login');
          return;
        }
        
        // 直接获取用户数量
        try {
          const usersCountResponse = await axios.get(`${API_URL}/users/count`, {
            headers: {
              'Authorization': `Bearer ${token}`,
              'x-auth-token': token
            }
          });
          
          if (usersCountResponse.data && typeof usersCountResponse.data.count === 'number') {
            userCount.value = usersCountResponse.data.count;
          }
        } catch (usersCountError) {
          console.error('获取用户数量失败');
        }
        
        // 首先尝试获取简化统计数据
        try {
          const simpleStats = await AdminService.getSimpleStats();
          
          if (simpleStats) {
            // 更新统计数字
            stats.totalPets = simpleStats.totalPets || 0;
            stats.totalUsers = simpleStats.totalUsers || 0;
            stats.pendingApplications = simpleStats.pendingApplications || 0;
            stats.successfulAdoptions = simpleStats.successfulAdoptions || 0;
            
            // 更新用户数量显示
            if (typeof simpleStats.totalUsers === 'number' && simpleStats.totalUsers > 0) {
              userCount.value = simpleStats.totalUsers;
            }
          }
        } catch (simpleError) {
          console.error('获取统计数据失败');
        }
        
        // 尝试获取申请趋势数据
        try {
          const trendData = await AdminService.getApplicationTrends();
          
          if (trendData) {
            chartData.applicationTrend.dates = trendData.dates || [];
            chartData.applicationTrend.counts = trendData.counts || [];
          }
        } catch (trendError) {
          console.error('获取趋势数据失败');
        }
        
        // 然后尝试获取完整统计数据
        try {
          const data = await AdminService.getDashboardStats();
          
          if (data) {
            // 更新统计数字
            if (typeof data.totalPets === 'number') stats.totalPets = data.totalPets;
            if (typeof data.totalUsers === 'number') stats.totalUsers = data.totalUsers;
            if (typeof data.pendingApplications === 'number') stats.pendingApplications = data.pendingApplications;
            if (typeof data.successfulAdoptions === 'number') stats.successfulAdoptions = data.successfulAdoptions;
            
            // 更新类别数据
            if (data.petCategories && Array.isArray(data.petCategories)) {
              chartData.categoryData = data.petCategories.map(cat => ({
                name: cat.name || '未知类别',
                value: cat.count || 0
              }));
              
              // 确保每个数据项都有正确的格式
              chartData.categoryData = chartData.categoryData.filter(item => 
                item.name && typeof item.value === 'number' && !isNaN(item.value)
              );
            }
            
            // 更新申请趋势（仅当之前的专用API失败时）
            if (chartData.applicationTrend.dates.length === 0 && data.applicationTrend) {
              chartData.applicationTrend.dates = data.applicationTrend.dates || [];
              chartData.applicationTrend.counts = data.applicationTrend.counts || [];
              
              // 确保日期和数量数组长度一致
              const minLength = Math.min(
                chartData.applicationTrend.dates.length,
                chartData.applicationTrend.counts.length
              );
              
              if (minLength > 0) {
                chartData.applicationTrend.dates = chartData.applicationTrend.dates.slice(0, minLength);
                chartData.applicationTrend.counts = chartData.applicationTrend.counts.slice(0, minLength);
              }
            }
            
            // 更新最近的申请
            if (data.recentApplications && Array.isArray(data.recentApplications)) {
              recentApplications.value = data.recentApplications;
            }
            
            // 更新待处理任务
            if (data.pendingTasks && Array.isArray(data.pendingTasks)) {
              todoItems.value = data.pendingTasks;
            }
            
            // 更新用户数量显示
            if (typeof data.totalUsers === 'number' && data.totalUsers > 0) {
              userCount.value = data.totalUsers;
            }
          }
        } catch (apiError) {
          console.error('获取统计数据失败');
        }
      } catch (error) {
        console.error('加载数据失败');
        ElMessage.error('加载统计数据失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 加载类别分布数据
    const loadCategoryDistribution = async () => {
      try {
        const response = await axios.get(`${API_URL}/pets/stats/category-distribution`);
        if (response.data && Array.isArray(response.data)) {
          // 确保数据格式正确
          chartData.categoryData = response.data.map(item => ({
            name: item.name || '未知类别',
            value: item.count || 0
          })).filter(item => 
            item.name && typeof item.value === 'number' && !isNaN(item.value)
          );
        }
      } catch (error) {
        console.error('获取类别分布数据失败');
        ElMessage.error('获取类别分布数据失败');
      }
    };
    
    // 组件挂载时加载数据
    onMounted(async () => {
      // 检查令牌
      const token = sessionStorage.getItem('token');
      if (!token) {
        console.error('认证错误');
        ElMessage.error('请先登录后再访问管理页面');
        router.push('/login');
        return;
      }
      
      try {
        // 加载统计数据
        await loadStats();
        
        // 加载最近评论
        await loadRecentComments();
        
        // 加载类别分布数据
        await loadCategoryDistribution();
        
        // 定期刷新数据(每5分钟刷新一次)
        const refreshInterval = setInterval(loadStats, 300000);
        
        // 组件卸载时清除定时器
        return () => {
          clearInterval(refreshInterval);
        };
      } catch (error) {
        console.error('加载数据失败');
        ElMessage.error('加载数据失败，请刷新页面重试');
      }
    });
    
    return {
      loading,
      stats,
      chartData,
      chartColors,
      recentApplications,
      todoItems,
      todoCategories,
      formatDate,
      formatStatus,
      getStatusType,
      navigateTo,
      viewApplication,
      actualUserCount,
      userCount,
      recentCommentsList,
      router
    }
  }
}
</script>

<style lang="scss" scoped>
@use "sass:color";

.admin-dashboard {
  min-height: calc(100vh - 200px);
  padding: 40px 0;
}

.loading-container {
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 100%;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-5px);
  }
}

.stat-card-content {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  
  i {
    font-size: 24px;
    color: white;
  }
}

.pets-icon {
  background-color: #409EFF;
}

.users-icon {
  background-color: #67C23A;
}

.applications-icon {
  background-color: #E6A23C;
}

.adoptions-icon {
  background-color: #F56C6C;
}

.stat-info {
  flex-grow: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--secondary-color);
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: var(--gray-color);
}

.stat-footer {
  text-align: right;
  border-top: 1px solid #eee;
  padding-top: 10px;
}

.charts-section,
.recent-section {
  margin-bottom: 20px;
}

.chart-card,
.recent-card {
  height: 100%;
}

.chart-header,
.recent-header,
.actions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
  }
}

.chart-container {
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.chart {
  width: 100%;
  height: 100%;
}

.chart {
  width: 100%;
  height: 100%;
}

.no-data {
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
  
  i {
    font-size: 40px;
    margin-bottom: 10px;
  }
  
  p {
    font-size: 14px;
  }
}

.comments-list {
  min-height: 100px;
  max-height: 400px;
  overflow-y: auto;
}

.comment-item {
  border-bottom: 1px solid #f0f0f0;
  padding: 12px 0;
  margin-bottom: 5px;
  &:last-child {
    border-bottom: none;
  }
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  
  strong {
    color: #409EFF;
    margin-right: 5px;
  }
  
  span {
    font-size: 0.9em;
    color: #606266;
  }
}

.comment-content {
  background-color: #f9f9f9;
  border-radius: 4px;
  padding: 8px 12px;
  margin: 5px 0;
  color: #303133;
  font-size: 0.95em;
  line-height: 1.5;
}

.comment-date {
  font-size: 0.8em;
  color: #909399;
  text-align: right;
  margin-top: 5px;
}

.todo-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100px;
  background-color: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s;
  cursor: pointer;
  
  i {
    font-size: 30px;
    color: var(--primary-color);
    margin-bottom: 10px;
  }
  
  span {
    font-size: 14px;
  }
  
  &:hover {
    background-color: color.adjust(#f8f9fa, $lightness: -10%);
  }
}

@media (max-width: 768px) {
  .stat-cards > div {
    margin-bottom: 15px;
  }
  
  .charts-section > div,
  .recent-section > div {
    margin-bottom: 15px;
  }
  
  .chart-container {
    height: 250px;
  }
}

.view-more-container {
  margin-top: 15px;
  text-align: center;
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.view-more-container .el-button {
  font-size: 14px;
}
</style>